package com.ifcar.app.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.http.HttpHost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.Splash;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.service.PushService;
import com.ifcar.app.activity.R;
import com.netease.util.Pair;

public class Tools {

	public static final String _BODY = "body";
	public static final String _TIME = "time";
	public static final String _TITLE = "title";
	public static final String _COMMENT_COUNT = "commentcount";
	public static final String _COMMENT_URL = "commenturl";
	public static final String _BOARD_ID = "boardid";
	public static final String _BAR = "bar";
	public static final String _DOCURL = "docURL";
	public static final String CTWAP = "ctwap";
	public static final String CMWAP = "cmwap";
	public static final String WAP_3G = "3gwap";
	public static final String UNIWAP = "uniwap"; 
	public static Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn"); 
	
	/**
	 * 获得新闻列表api里面的扩展域
	 * @param orgjson
	 * @return
	 */
	public static JSONObject getExtendJson(JSONObject orgjson){
	    
	    JSONObject exjson = new JSONObject();
        for(int exindex=0;exindex<GetColumnsInfo.EXTENDS.length;exindex++){
            try {
                String key = GetColumnsInfo.EXTENDS[exindex];
                Object obj = orgjson.get(key);
                if(null!=obj){
                    exjson.put(key, obj);
                }
            } catch (JSONException e) {
                
            }
        }
        return exjson;
        
	}
	
	/**
     * 设置proxy
     * @param proxy
     * @param port
     */
    public static void setHttpProxy(String proxy, String port) {     
        Properties systemProperties = System.getProperties();
        systemProperties.setProperty("http.proxyHost",proxy);
        systemProperties.setProperty("http.proxyPort",port);  
    }
	
    /**
     * 是否显示图片
     * downpic=ture 表示禁止在3G/2G网络下图但是wifi是可以下图的
     * downpic=false 表示在所有网络情况下都可以下图
     */
	public static boolean isshowimg(boolean downpic,Context c){
		boolean rst = false;
		
		if(isWifi(c)){
			rst = true;
		}else{
			
			if(!downpic){
				rst = true;
			}else{
				rst = false;
			}
		}
		return rst;
	}
	
	/**
	 * 判断是否是带有头图的栏目
	 * @param columnID
	 * @return
	 */
	public static String equalHead(String columnID){
		String rst = "nonhead";
		if(isOrderByPoint(columnID)){
			rst = "head";
		}
		return rst;
	}
	
	/**
	 * 按权重排序的栏目
	 * @param columnID
	 * @return
	 */
	public static boolean isOrderByPoint(String columnID){
	    if("T1295505916992".equals(columnID) 
                || "T1295506658957".equals(columnID)
                || "T1295505705196".equals(columnID)
                || "T1295507084100".equals(columnID)
                ||"T1295501906343".equals(columnID)
                ||StringUtil.COLUMN_TOPIC_COMMENT.equals(columnID)
                ||StringUtil.COLUMN_TOPIC_BLOG.equals(columnID)
                ||StringUtil.COLUMN_TOPIC_BBS.equals(columnID)
                ||StringUtil.COLUMN_TOPIC_DUJIA.equals(columnID)
                ||StringUtil.COLUMN_TOPIC_ANOTHER.equals(columnID)
                ||StringUtil.COLUMN_TOPIC_SPECIALI.equals(columnID)
                ||StringUtil.COLUMN_TOPIC_DIGIT.equals(columnID)){
	        return true;
	    }else{
	        return false;
	    }
	}
	
	/**
	 * 判断来自于新闻栏目带头图的栏目
	 * @param columnID
	 * @return
	 */
	public static boolean isColumnWithImgFromNews(String columnID){
	    if("T1295505916992".equals(columnID) 
                || "T1295506658957".equals(columnID)
                || "T1295505705196".equals(columnID)
                || "T1295507084100".equals(columnID)
                ||"T1295501906343".equals(columnID)
                ||"T1337596068742".equals(columnID)){
	        return true;
	    }else{
	        return false;
	    }
	}
	
	/**
	 * 添加导航中的一个栏目
	 * @param context
	 * @param title
	 * @return
	 */
	public static LinearLayout addColumnTypeTitle(Context context, String title) {
		LinearLayout l = new LinearLayout(context);
		l.setBackgroundResource(R.color.text_color);
		TextView t = new TextView(context);
		t.setText(title);
		t.setPadding(5, 5, 5, 5);
		l.addView(t, new LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		return l;
	}
	
	/**
	 * 查询某个表的所有数据
	 * @param context
	 * @param table
	 * @param db
	 * @return
	 */
	public static Cursor getDataFromDB(Context context, String table,
			SQLiteDatabase db) {
		return db.query(table, new String[] { NewsSQLiteOpenHelper.MYID
				+ " AS _id," + NewsSQLiteOpenHelper.TNAME + ","
				+ NewsSQLiteOpenHelper.TID + "," + NewsSQLiteOpenHelper.CID },
				null, null, null, null, null, null);
	}

	/**
	 * 
	 * @param table
	 * @param db
	 * @param tname
	 * @param tid
	 * @param cid
	 */
	public static void insertDataToDB(String table, SQLiteDatabase db,
			String tname, String tid, String cid) {
		ContentValues initialValues = new ContentValues();
		initialValues.put(NewsSQLiteOpenHelper.TNAME, tname);
		initialValues.put(NewsSQLiteOpenHelper.TID, tid);
		initialValues.put(NewsSQLiteOpenHelper.CID, cid);
		db.insert(table, null, initialValues);
	}
    
	/**
	 * Json 转换为 String
	 * @param json
	 * @return String
	 */
	public static String JsonToString(JSONObject json){
		
		if(null!=json){
			
			return json.toString();
		}else{
			
			return "";
		}
		
	}
    /**
     * String 转换为 Json
     * @param str
     * @return Json
     */
    public static JSONObject StringToJson(String str){
		
		if(null!=str){
			try {
				JSONObject json = new JSONObject(str);
				return json;
			} catch (JSONException e) {
				return null;
			}
		}else{
			
			return null;
		}
	}
	
    /**
     * String 转换为 JSONArray
     * @param str
     * @return JSONArray
     */
	public static JSONArray StringToJsonArray(String str){
		
		if(null!=str){
			try {
				 JSONArray jsonArray = new JSONArray(str);
				return jsonArray;
			} catch (JSONException e) {
				return null;
			}
		}else{
			
			return null;
		}
	}

	/**
	 * 字符替换
	 * @param src
	 * @param fnd
	 * @param rep
	 * @return String
	 * @throws Exception
	 */
	public static String replaceAll(String src, String fnd, String rep)
			throws Exception {
		if (src == null || src.equals("")) {
			return "";
		}

		String dst = src;

		int idx = dst.indexOf(fnd);

		while (idx >= 0) {
			dst = dst.substring(0, idx) + rep
					+ dst.substring(idx + fnd.length(), dst.length());
			idx = dst.indexOf(fnd, idx + rep.length());
		}

		return dst;
	}

	/**
	 * 替换HTML字符.
	 */
	public static String htmlDecoder(String src) throws Exception {
		if (src == null || src.equals("")) {
			return "";
		}

		String dst = src;
		dst = replaceAll(dst, "&lt;", "<");
		dst = replaceAll(dst, "&rt;", ">");
		dst = replaceAll(dst, "&gt;", ">");
		dst = replaceAll(dst, "&quot;", "\"");
		dst = replaceAll(dst, "&039;", "'");
		dst = replaceAll(dst, "&nbsp;", " ");
		dst = replaceAll(dst, "&nbsp", " ");
		dst = replaceAll(dst, "<br>", "\n");
		dst = replaceAll(dst, "<BR>", "\n");
		dst = replaceAll(dst, "\r\n", "\n");
		dst = replaceAll(dst, "&#8826;", "•");
		dst = replaceAll(dst, "&#8226;", "•");
		dst = replaceAll(dst, "&#9642;", "•");
		dst = replaceAll(dst, "&amp;", "&");
		dst = replaceAll(dst, "<br/>", "");
		dst = replaceAll(dst, "<BR/>", "");
		return dst;
	}	
	
	public static String FilterCNSpace(String src) throws Exception{
	    String dst = src;
	    dst = replaceAll(dst,"　","");
	    return dst;
	}
	
	/**
	 * @param s 源字符串
	 * @param srcString 需要替换的字符串
	 * @param dstString 替换后的字符串
	 * @return
	 */
	public static String replace(String s, String srcString, String dstString) {
		if (s == null || s.equals("")) {
			return "";
		}

		String d = s;
		try {
			d = replaceAll(d, srcString, dstString);
		} catch (Exception e) {
			// TODO Auto-generated catch block
		}
		return d;
	}
	
	/**
	 * 获取跟贴数据中用户名
	 * @param src
	 * @return
	 */
	public static String getUserName(String src) {
		if (src == null || src.equals("")) {
			return "";
		}
		StringBuilder s = new StringBuilder(src);
		if(src.startsWith("网易")) {
			s = s.delete(0, 2);
		}
		
		if(src.contains("原贴")) {
			src = s.substring(0, s.indexOf("网友")+2) + " 的原贴：";
		} else {
			src = s.substring(0, s.indexOf("网友")+2) + "：";
		} 
			
		return src;
	}

	/**
	 * 获取手机分辨率宽度大小
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getApplicationContext().getResources().getDisplayMetrics();
		return dm.widthPixels;
	}

	/**
	 *  返回屏幕的规格
	 *  0 为其他尺寸 
	 *  1 为 320*240
	 *  2 为 480*320
	 *  3 为 480*800
	 *  4 为 640*960
	 * @param c
	 * @return
	 */
	public static int getScreenMetrics(Context c){
		int type = 0;
		DisplayMetrics metrics = new DisplayMetrics();
		metrics = c.getApplicationContext().getResources().getDisplayMetrics();		
		
		int width = metrics.widthPixels;
		int height = metrics.heightPixels;
		
		if(width==480 && height == 800)
            type = 3;
        else if(width==320 && height == 480)
            type = 2;
        else if(width==240 && height == 320)
            type = 1;
        else if(width==640 && height == 960)
            type = 4;
        else if(width==720)
            type = 5;

		return type;
	}
	
	/**
	 * 根据屏幕宽度换算出头图图片所需下载的高度
	 * @param width
	 * @return
	 */
	public static int getHeadPicHeight(int width){
	    
	    if(width<=0){
	        return 0;
	    }else{
	        return ((width*3)/4);
	    }
	    
	}
	
	/**
     * 根据屏幕宽度换算出头图图片所需裁剪高度
     * @param width
     * @return
     */
	public static int getCutHeadPicHeight(int width){
	    if(width<=0){
	        return 0;
	    }else if(width<=240){
	        return 90;
	    }else{
	        return (width*255)/480;
	    }
	}
	
	/**
     * 根据屏幕宽度换算出专题banner图片所需裁剪高度
     * @param width
     * @return
     */
	public static int getSpecialBannerCutHeadPicHeight(int width){
        if(width<=0){
            return 0;
        }else if(width<=240){
            return 44;
        }else{
            return (width*126)/480;
        }
    }
	
	/**
	 * 获取手机屏幕的宽和高
	 * @param c
	 * @return map("w",width) map("h",height);
	 */
	public static HashMap<String,Integer> getWidth_Height(Context c){
	    DisplayMetrics metrics = new DisplayMetrics();
        metrics = c.getApplicationContext().getResources().getDisplayMetrics(); 
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;
        
        HashMap<String,Integer> m = new HashMap<String,Integer>();
        m.put("w", width);
        m.put("h", height);
        return m;
	}
	
	/**
	 * 获取网络类型
	 * @param mContext
	 * @return
	 */
	public static String getNetworkType(Context mContext){
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext  
        .getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
        if (activeNetInfo != null){
            return activeNetInfo.getTypeName();
        }else{
            return "other";
        }
    }
	
	/**
	 * 检查当前网络是否可用
	 * @param context
	 * @return
	 */
	public static boolean CheckNetwork(Context context) {
	    
	    boolean flag = false;
	    ConnectivityManager cwjManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	    if (cwjManager.getActiveNetworkInfo() != null)
	        flag = cwjManager.getActiveNetworkInfo().isAvailable();
	    
	    return flag;
	}
	
	/**
	 * 判断当前网络是否是wifi
	 * @param mContext
	 * @return
	 */
	public static boolean isWifi(Context mContext) {  
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext  
		             .getSystemService(Context.CONNECTIVITY_SERVICE);  
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
		if (activeNetInfo != null  
		             && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {  
		        return true;  
		     }  
		return false; 
	}
	
	/**
	 * 判断当前网络是否是wap
	 * @param mContext
	 * @return
	 */
	public static boolean isCMWAPMobileNet(Context mContext){
	    
	    if(null==mContext){
	        return false;
	    }
		
		if(isWifi(mContext)){
			return false;
		}else{
			ConnectivityManager mag = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
			
			if(null!=mag){
				NetworkInfo mobInfo = mag.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				if(null!=mobInfo){
				    String extrainfo = mobInfo.getExtraInfo();
				    if(null!=extrainfo){
				        extrainfo = extrainfo.toLowerCase();
				        if(extrainfo.contains("wap")){
				            return true;
				        }else{
				            return false;
				        }
				    }else{
				        return false;
				    }

				}else{
					return false;
				}
			}else{
				return false;
			}
		}
		
	}
	
	/**
	 * 获取wap网络条件下的代理服务器，如果为非wap返回为空对象
	 * @param mContext
	 * @return
	 */
	public static String getHostbyWAP(Context mContext){
	    
	    if(null==mContext){
            return null;
        }
	    
	    if(Tools.isWifi(mContext)){
	        return null;
	    }
	    
	    try {
            String result = null; 
            ConnectivityManager mag = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            if(null!=mag){
                NetworkInfo mobInfo = mag.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
                if(null!=mobInfo){
                    
                    String extrainfo = mobInfo.getExtraInfo();
                    if(null!=extrainfo){
                        extrainfo = extrainfo.toLowerCase();
                        if(extrainfo.equals(CMWAP) || extrainfo.equals(WAP_3G)|| extrainfo.equals(UNIWAP)){//移动 or 联通wap代理
                            result = "10.0.0.172";
                        }else{
                            //电信WAP判断
                            final Cursor c = mContext.getContentResolver().query(PREFERRED_APN_URI, null, null, null, null); 
                            if (c != null) { 
                                c.moveToFirst(); 
                                final String user = c.getString(c.getColumnIndex("user")); 
                                if (!TextUtils.isEmpty(user)) { 
                                    if (user.toLowerCase().startsWith(CTWAP)) {
                                        result = "10.0.0.200";
                                    }
                                }
                                c.close(); 
                            }
                            
                        }
                    }
                }
            }
            return result;
        } catch (Exception e) {
            return null;
        }
	    
	}
	
	/**
	 * 根据网络环境判断是否给httpclient设置代理
	 * @param httpclient
	 * @param mContext
	 */
	public static void setHttpClientHostProxy(DefaultHttpClient httpclient,Context mContext){
	    
	    if(null==httpclient){
            return;
        }
	    
	    String host = getHostbyWAP(mContext);
	    if(null!=host){
	        HttpHost proxy = new HttpHost(host, 80, "http");
	        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
	    }else{
	        httpclient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
	    }
	    
	}
	
	/**
	 * 从url获取含有key的参数值
	 * @param url
	 * @param key
	 * @return
	 */
	public static String parseURL(String url,String key){
	    
	    String rst = "";
	    
	    if(null==key || "".equalsIgnoreCase(key)){
	       
	    }else{
	        
	        int i = url.indexOf("?");
            if(i+1<=url.length()){
                
               String param =  url.substring(i+1,url.length());
               String[] values =  param.split("&");
               if(null!=values){
                   
                   for(int index=0;index<values.length;index++){
                       
                       if(values[index].contains(key)){
                           
                           String[] keys = values[index].split("=");
                           
                           if(keys.length>1){
                               rst = keys[1];
                               break;
                           }
                       }
                   }
               }
               
            }
	    }
	    
	    return rst;
	}
	
	/**
	 * 组合有道图片缩略服务url
	 * @param url
	 * @return
	 */
	public static String getSuitableImageUrl(String url){
		String rst ="";
		int cdn = (int)(Math.random()*8+1);
		rst = "http://oimagec"+cdn+".ydstatic.com/image?url="+url;
		return rst;
	}
	
	/**
	 * 专题页面数据分组
	 * @param orglist
	 * @return
	 */
	public static List<Pair<String, List<Map<String, Object>>>> toGropuList4Special(List<Map<String, Object>> orglist){
	    
	    List<Map<String, Object>> child = new ArrayList<Map<String, Object>>();
	    String groupstr = "";
	    String agogroupstr = "";
	    List<Pair<String, List<Map<String, Object>>>> group  = new ArrayList<Pair<String, List<Map<String, Object>>>>(); 
	    
	    if(null!=orglist && orglist.size()>0){
	       int sum = orglist.size();
	       
	       for(int index=0;index<sum;index++){
	           
	           Map<String, Object>  one = orglist.get(index);
	           
	           String special_index_tag = (String)one.get(GetColumnsInfo.SPECIAL_INDEX_TAG);
	           if(!"0".equals(special_index_tag)){
	               
	               groupstr = (String)one.get(GetColumnsInfo.SPECIAL_TNAME_TAG);
	               if("".equals(agogroupstr)){
	                   agogroupstr = groupstr;
	               }
	               
	               if(!"".equals(groupstr)||index==sum-1){
	                   
	                   if(index==sum-1) child.add(one);
	                   
	                   if(child.size()>0){
	                       
	                       Pair<String, List<Map<String, Object>>> p = Pair.create(agogroupstr, child);
                           group.add(p);
                           child = new ArrayList<Map<String, Object>>();
                           agogroupstr = groupstr;
	                   }
	                   
	                   
	                   if(index<sum-1){
	                       child.add(one);
	                   }
	                   
	               }else{
	                   child.add(one);
	               }
	               
	           }
	       }//end get group
	        
	    }
	    
        return group;
	}
	
	/**
	 * 变更置换当前容器数据
	 * @param orglist
	 */
	public static void ChangeList(ArrayList<HashMap<String, Object>> orglist){
        ArrayList<HashMap<String, Object>> temp = new ArrayList<HashMap<String, Object>>();
        temp.addAll(orglist);
        orglist.clear();
        orglist.addAll(temp);
        temp.clear();
        temp = null;
    }
	
	/**
	 * 判断是否为平板
	 * @return
	 */
	public boolean isHoneycomb(){
	    
	    return Build.VERSION.SDK_INT>=11;
	    
	}
	
	/**
	 * 获得支持ACTION_SEND的应用列表 
	 * @param mContext
	 * @param type
	 * @return
	 */
    public static  List<ResolveInfo> getShareTargets(Context mContext,String type){
        Intent intent=new Intent(Intent.ACTION_SEND);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType(type);
        PackageManager pm=mContext.getPackageManager();
    
        return pm.queryIntentActivities(intent,
        PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
    }
	
    /**
     * 复制文字
     * @param context
     * @param str
     */
    public static void copyText(Context context, String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }

        ClipboardManager clipboard = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(str);
        Toast.makeText(context, "已复制跟贴", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 获得URL的host
     * @param url
     * @return
     */
    public static String getHost(String url){
        if(null==url || "".equals(url)){
            return "";
        }else{
            try {
                String newurl = url.replace("http://", "");
                newurl = newurl.substring(0,newurl.indexOf("/"));
                return newurl;
            } catch (Exception e) {
                return "";
            }
        }
    }
    
    /**
     * 转换图集列表封面 在头条头图里面的图集
     * @param cover
     * @return
     */
    public static String transformPhotoSetCover(String cover){
        String dst = cover;
        if(null!=cover && !"".equals(cover)){
            int last = dst.lastIndexOf("/");
            if(last<cover.length()-1){
                dst = dst.substring(0, last+1)+"400x400_"+dst.substring(last+1);
            }
        }
        return dst;
    }
    
    /**
     * 设置里面检查更新
     * @param context
     * @return
     */
    public static Map checkAppUpdate(Context context){
        String title, message, version, type;
        String result = HttpUtils.getResponseFromGetUrl4GBK(StringUtil.NOTICEURL, 2500, context);
        JSONObject obj = null;
        Map rst = null;
        try {
            obj = new JSONObject(result);
            if(null!=obj){
                version = obj.getString("app_version");
                title = obj.getString("title");
                message = obj.getString("content");
                type = obj.getString("type");
                String oversion = context.getResources().getString(R.string.versionnum);
                oversion = oversion.substring(1);
                
                if("update".equals(type)){
                    long nv = 0l; 
                    long ov = 0l;
                    nv = Long.parseLong(version.replace(".", ""));
                    ov = Long.parseLong(oversion.replace(".", ""));
                    if(nv>ov){
                        rst = new HashMap();
                        rst.put("title", title);
                        rst.put("message", message);
                    }
                }
            }
        } catch (Exception e) {
            
        }
        return rst;
    }
    
    
 public static String getSoftwareSize(long size){
        
        String rst = "0.00M";
        
        
        if(size<1024*1024){
            rst = ""+(size/1024)+"K";
        }else{
            String temp = ""+size%1048576;
            if(temp.length()>2){
                temp = temp.substring(0, 2);
            }
            rst = ""+(size/1048576)+"."+temp+"M";
        }
            
        return rst;
        
    }
 
 public static String getChannel(String column){
     String channel = "0096";
     if(null!=column && column.length()>=8){
         channel = column.substring(column.length()-4,column.length());
     }
     return channel;
 }
    
}
